define(["jquery",'layer',"ELEMENT","ELEMENTICON",'ELEMENTCN','install'],function ($,layer,ELEMENT,ELEMENTICON,ELEMENTCN,install){
    var temHeight = 0
    var common = {
        /**
         * 加载element图标
         * @param app
         */
        loadELEMENTIcon(app){
            for (const [key, component] of Object.entries(ElementPlusIconsVue)){
                // console.log(key,'key')
                if(this.allIcon&&this.allIcon.indexOf(key)!=-1){
                    that.allIcon.push(key)
                }
                app.component(key, component)
            }
        },
        // 获取element图标
        getELEMENTIcon(){
            let icon_list = []
            for (const [key, component] of Object.entries(ElementPlusIconsVue)){
                icon_list.push(key)
            }
            return icon_list
        },
        /**
         * 加载element
         * @param app
         */
        loadELEMENT(app,plug= ['all']){
            // console.log(plug)
            if(plug===false){
                plug = []
            }
            app.use(ELEMENT,{
                locale: ELEMENTCN // 注入中文语言包
            });
            this.loadELEMENTIcon(app);//加载图标
            install.install(app,plug)
            // muimg.install(app)
            // app.use(ELEMENTEDITOR);//加载富文本编辑器
        },
        //富文本编辑器添加数据
        updateBianji(value,field){
            this.form[field] = value
            console.log(this.form)
        },
        // 添加主模块
        addMain(name,module,route,key){
            // console.log(key)
            // console.log(name,module,route,key,'addMain')
            if(route.indexOf('?')==-1){
                route = route+'?ref=addtabs'
            }else{
                route = route+'&ref=addtabs'
            }
            let main_config = this.main_config;
            if(main_config.length>0){
                let that = this
                let has = false
                main_config.forEach((item)=>{
                    if(item.key==key){
                        that.select_main = item
                        has = true
                    }
                })
                if(has){
                    this.selectMainUrl()
                    return
                }
            }
            this.main_config.push({
                title: name,
                url:route,
                key:key,
                module:module
            })
            this.select_main = {
                title: name,
                url:route,
                key:key,
                module:module
            }
            this.selectMainUrl()

        },
        /**
         * 创建搜索数据
         */
        loadSeach(){
            let seachObj = this.seachObj
            let show = false
            seachObj.forEach((item)=>{
                if(item.show){
                    show = true
                }
            })
            this.seachShow = show
        },
        // 选择主模块
        selectMainUrl(){
            let main_config = this.main_config
            // console.log(main_config)
            let select_main = this.select_main;
            console.log(select_main,'select_main')
            if(select_main?.key){
                let that = this
                main_config.forEach((item,index)=>{
                    if(item.key==select_main.key){
                        that.activeName = item.key
                    }
                })
            }
            if(select_main?.url){
                this.setRoute(select_main.url)
            }
        },
        setRoute(route){
            let href = location.href
            href = href.split('?')[0]
            if(href.indexOf('#')>-1){
                href = href.split('#')[0]
            }
            if(route){
                href = href+'#'+'/'+route
                // console.log(href)
                history.replaceState({ page: href }, '', href);
            }
        },
        /**
         * post请求
         * @param url
         * @param data
         * @param callback
         */
        modulePost(url,data,callback=null){
            if(!callback){
                if((typeof data)==='function'){
                    callback = data
                    data = null
                }
            }
            layer.load(0)
            url = Config.moduleurl + '/' + url
            $.post(url,data,function (res){
                layer.closeAll('loading')
                if(res.code==1){
                    that.$message({
                        message: res.msg,
                        type: 'success'
                    })
                    if(callback){
                        callback(res.data)
                    }

                }else{
                    that.$message({
                        message: res.msg?res.msg:'操作失败',
                        type: 'error'
                    })

                }
            })
        },
        confirm(message='',callback=null,type='warning'){
            this.$messageBox.confirm(message,'警告',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(function () {
                if(callback){
                    callback()
                }
            }).catch(function () {
                console.log("取消")
            })
        },
        /**
         * 刷新数据
         */
        handleRefresh(){
          this.indexLoadData()
        },
        /**
         * 切换开关
         * @param status
         * @param row
         * @param field
         */
        changeSwitich(status,row,field){
            let that = this;
            let url = Config.moduleurl+'/'+(this.urls&&this.urls.multi_url?this.urls.multi_url:Config.controllername+'/multi')+`?ids=${row[this.pk]}`
            $.post(url,{params:`${field}=${status}`,action:"",ids:row[this.pk]},function (res){
                if(res.code==1){
                    return true
                }else{
                    that.$message({
                        message: res.msg,
                        type: 'error'
                    })
                    let rows = that.dataObj.rows;
                    rows.forEach(item=>{
                        if(item.id==row.id){
                            item[field] = !status
                        }
                    })
                    that.dataObj.rows = rows
                }
            })
        },
        /**
         * 创建搜索数据
         * @param data
         * @returns {{}}
         */
        createSeachParams(data){
            // return {}
            data = JSON.parse(JSON.stringify(data))
            let params = {}
            let filter = {}
            let notIn=[
                'sort',
                'order',
                'offset',
                'limit',
                'page',
                'keyField',
                'q_word',
                'keyValue',
                'showField',
                'searchField',
                'custom',
                'isTree',
                'isHtml',
                'orderBy',
                'andOr',
                'pageSize',
                'pageNumber',
            ]
            let op = {}
            let sub_type = {}
            data.forEach(item=>{
                if(!notIn.includes(item.field)){
                    if(!(item.value==''||item.value==null)){
                        if(Array.isArray(item.value)){
                            // console.log("数组------------------------")
                            let has = false
                            item.value.forEach(item2=>{
                                if(item2!=''){
                                    has = true
                                }
                            })
                            if(has===true){
                                filter[item.field] = item.value
                                op[item.field] = item.type?item.type:'='
                                sub_type[item.field] = item.sub_type?item.sub_type:'string'
                            }
                        }else{
                            filter[item.field] = item.value
                            op[item.field] = item.type?item.type:'='
                            sub_type[item.field] = item.sub_type?item.sub_type:'string'
                        }
                    }

                }else{
                    params[item.field] = item.value
                }
            })
            params.filter = JSON.stringify(filter)
            params.op = JSON.stringify(op)
            params.sub_type = JSON.stringify(sub_type)
            return params;
        },
        /**
         * 带模块的get请求
         * @param url
         * @param data
         * @param callback
         */
        moduleGet(url,data,callback=null){
            if(!callback){
                if((typeof data)==='function'){
                    callback = data
                    data = null
                }
            }
            layer.load(0)
            url = Config.moduleurl + '/' + url
            if(url.includes('?')===false){
                if(data!=={}&&data!==null&&data!==undefined&&data!==''){
                    url = url+'?'+$.param(data)
                }
            }else{
                if(data!=={}&&data!==null&&data!==undefined&&data!==''){
                    url = url+'&'+$.param(data)
                }
            }
            $.post(url,function (res){
                layer.closeAll('loading')
                if(callback){
                    callback(res)
                }
            })
        },
        // post提交
        post(url,data,callback=null,loading=true){
            if(!callback){
                if((typeof data)==='function'){
                    callback = data
                    data = null
                }
            }
            url = Config.baseUrl.trimEnd('/') + '/' + url.trimStart('/')
            let loadObj = null
            if(loading){
                loadObj = this.$loading()
            }
            $.post(url,data,function (res){
                if(loadObj){
                    loadObj.close()
                }
                if(res.code==1){
                    that.$message({
                        message: res.msg,
                        type: 'success'
                    })
                    if(callback){
                        callback(res.data)
                    }

                }else{
                    if(res.msg){
                        that.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }else{
                        that.$message({
                            message: "操作失败",
                            type: 'error'
                        })
                    }

                }
            })
        },
        /**
         * 数据复制
         * @param data
         * @returns {any}
         */
        copy(data){
            return JSON.parse(JSON.stringify(data))
        },
        //关闭窗口
        handleCancel(){
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },
        //表单提交
        onSubmit(){
            // console.log(99999999999999)
            let url = Config.sub_url;
            let form = this.copy(this.form)
            let data = {row:form}
            if(this.additional){
                data = {...data,...this.additional}
            }
            let that = this;
            console.log(url,99999999999999)
            if(url){
                // layer.load(0);
                if(this.rules){
                    if(this.rules!={}&&this.rules!=null){
                        this.$refs.form.validate((valid) => {
                            if(valid){
                                let loadObj = that.$loading();
                                $.post(url,data,function (res){
                                    loadObj.close()
                                    if(res.code==1){
                                        that.$message({
                                            message: res.msg?res.msg:"操作成功",
                                            type: 'success'
                                        })
                                        var index = parent.layer.getFrameIndex(window.name);
                                        if(parent.success){
                                            parent.success()
                                        }
                                        if(parent.cancel){
                                            parent.cancel()
                                        }
                                        if(parent.close){
                                            parent.close()
                                        }
                                        if(parent.callback){
                                            parent.callback()
                                        }
                                        setTimeout(function () {
                                            parent.layer.close(index);
                                        },1000)
                                    }else{
                                        that.$message({
                                            message: res.msg?res.msg:"操作失败",
                                            type: 'error'
                                        })
                                    }
                                })
                            }
                        });
                        return
                    }
                }else{
                    let loadObj = that.$loading();
                    $.post(url,data,function (res){
                        loadObj.close()
                        if(res.code==1){
                            that.$message({
                                message: res.msg?res.msg:"操作成功",
                                type: 'success'
                            })
                            var index = parent.layer.getFrameIndex(window.name);
                            if(parent.success){
                                parent.success()
                            }
                            if(parent.cancel){
                                parent.cancel()
                            }
                            if(parent.close){
                                parent.close()
                            }
                            if(parent.callback){
                                parent.callback()
                            }
                            setTimeout(function () {
                                parent.layer.close(index);
                            },1000)
                        }else{
                            that.$message({
                                message: res.msg?res.msg:"操作失败",
                                type: 'error'
                            })
                        }
                    })
                }
            }
        },
        uploaderParameter(){
            // console.log(Config)
            return {
                mymodule:Config.modulename,
            }
        },
        /**
         * 添加数据
         */
        handleAdd(obj=null){
          // console.log(Config,'-----------------')
            let url = Config.domain+Config.base_url+'/add'
            // if(Config.apps.includes(Config.modulename)){
            //     url = Config.controllername+'/add'
            // }else{
            //     url = Config.domain+Config.moduleurl+'/'+Config.controllername+'/add'
            // }

            // console.log(url,Config,'uuuuuuuuuuuuuuuuuuuuuuuuuuuuu')
            // return
            let that = this;
            let callback = obj?.callback||null
            this.open2(url,{
                title:obj?.title?obj.title:'添加',
                area:obj?.area?obj.area:['50%','90%'],
                callback:callback?callback:function (res){
                    that.indexLoadData()
                }
            })
        },
        handleShowAttachment(field,multiple=0){
            // console.log(Config,'==========================')
            let url = Config.domain+Config.attachment_url+`?select=1&multiple=${multiple}`
            let that = this;
            this.open2(url,{
                area:['100%','100%'],
                title:"选择图片",
                callback:function (res){
                    that.form[field] = res
                    // console.log(res,'rrrrrrrrrrrrrrrrrrrr')
                    // that.indexLoadData()
                }
            })
        },
        /**
         * 编辑数据
         * @param row
         * @param pk
         */
        handleEdit(row,pk='id',obj=null){
            let url = Config.domain+Config.base_url+`/edit?ids=${row[pk]}`
            console.log(url)
            // return
            // let url = Config.controllername+`/edit?ids=${row[pk]}`
            let that = this;
            let callback = obj?.callback||null
            this.open2(url,{
                title:obj?.title?obj.title:"修改",
                area:obj?.area?obj.area:['50%','90%'],
                callback:callback?callback:function (res){
                    that.indexLoadData()
                }
            })
        },
        handleSelectionChange(row,pk='id'){
            // console.log(row)
            let selectIds = []
            row.forEach(item=>{
                selectIds.push(item[pk])
            })
            this.selectIds = selectIds
        },
        // 批量删除
        handleDeleteAll(){
            let selectIds = this.selectIds
            if(Array.isArray(selectIds)){
                selectIds = selectIds.join(',')
            }
            let url =Config.domain+Config.base_url+`/del?ids=${selectIds}`
            let that = this;
            this.$messageBox.confirm('确定删除吗？','警告',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                let loadObj = this.$loading();
                $.post(url,function (res){
                    loadObj.close()
                    if(res.code==1){
                        that.$message({
                            message: res.msg?res.msg:"删除成功",
                            type: 'success'
                        })
                        that.indexLoadData()
                    }else{
                        that.$message({
                            message: res.msg?res.msg:"操作失败",
                            type: 'error'
                        })
                    }
                })
            }).catch(e=>{
                that.$message({
                    message:  res.msg?res.msg:"操作失败",
                    type: 'error'
                })
            })
            // layer.confirm('确定删除吗？', function(index){
            //     if(index){
            //         $.post(url,function (res){
            //             if(res.code==1){
            //                 that.$message({
            //                     message: res.msg?res.msg:"删除成功",
            //                     type: 'success'
            //                 })
            //                 that.indexLoadData()
            //             }else{
            //                 that.$message({
            //                     message: res.msg?res.msg:"操作失败",
            //                     type: 'error'
            //                 })
            //             }
            //         })
            //     }
            // })
        },
        /**
         * 删除数据
         * @param row
         * @param pk
         */
        handleDelete(row,pk='id'){
            let url = Config.domain+Config.base_url+`/del?ids=${row[pk]}`
            // console.log(url,Config)
            // return
            let that = this;
            this.$messageBox.confirm('确定删除吗？','警告',{
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(()=>{
                let loadObj = this.$loading();
                $.post(url,function (res){
                    loadObj.close()
                    // console.log(res)
                    if(res.code==1){
                        that.$message({
                            message: res.msg?res.msg:"删除成功",
                            type: 'success'
                        })
                        that.indexLoadData()
                    }else{
                        that.$message({
                            message: res.msg?res.msg:"操作失败",
                            type: 'error'
                        })
                    }
                })
            }).catch((e)=>{
                this.$message({
                    type: 'error',
                    message: e.msg?e.msg:'已取消删除'
                });
            })
            // layer.confirm('确定删除吗？', function(index){
            //     if(index){
            //         $.post(url,function (res){
            //             console.log(res)
            //             if(res.code==1){
            //                 that.$message({
            //                     message: res.msg?res.msg:"删除成功",
            //                     type: 'success'
            //                 })
            //                 that.indexLoadData()
            //             }else{
            //                 that.$message({
            //                     message: res.msg?res.msg:"操作失败",
            //                     type: 'error'
            //                 })
            //             }
            //         })
            //     }
            // })
        },
        selectable(row){
            return true;
        },
        //修改每页数量
        handleSizeChange(e){
            this.dataObj.limit = e
            this.indexLoadData()
        },
        //跳转分页
        handleCurrentChange(e){
          // console.log(e)
            this.dataObj.page = e
            this.indexLoadData()
        },
        /**
         * index页面加载数据
         */
        indexLoadData(){
            let seachObj = this.seachObj||{};
            if(seachObj&&seachObj!==null&&seachObj!==undefined&&seachObj!==''&&JSON.stringify(seachObj)!=="[]"&&JSON.stringify(seachObj)!=="{}"){
                seachObj = common.createSeachParams(seachObj)
            }
            console.log(Config,'cccccccccccc')
            // console.log(seachObj)
            // return
            // console.log(seachObj,'sssssssssssssssssssssssssss',Config.sub_url)
            seachObj.page = this.dataObj.page
            seachObj.limit = this.dataObj.limit
            let that = this;
            $.get(Config.sub_url,seachObj,function (res){
                // console.log(res,'rrrrrrrrrrrrrrrrr')
                // if(res.rows.length>0){
                //     that.dataObj.page += 1
                // }
                that.dataObj.rows = res.rows
                that.dataObj.total = res.total
            })
        },
        handleSeach(){
            this.dataObj.page = 1
            console.log(this.seachObj)
            this.indexLoadData()
        },
        /**
         * 重置搜索
         */
        handleReset(){
            this.seachObj.forEach(item=>{
                if(item.seachType=='datetimerange'){
                    item.value = ["",""]
                }else{
                    item.value = ""
                }
            })
            this.handleSeach()
        },
        /**
         * 创建高度
         */
        indexCreateHeight(num=0){
            if(temHeight==0){
                temHeight = num
            }
            console.log(num)
            let that = this;
            setTimeout(()=>{
                that.height =  document.body.clientHeight + num -130
                // console.log(that.height,document.body.clientHeight)
            },50)
        },
        getEditData(pk='id',callback){
          // console.log(Config,'ccccccccccccccccc')
            let url = Config.moduleurl+'/'+Config.controllername+`/index`;
          // console.log(url)
            let ob = this.getQueryParameterAsJson()
            let that = this;
            // console.log(ob,'oooooooooooooo')
            if(ob&&ob.ids){
                let data = {
                    keyField:pk,
                    keyValue:ob.ids
                };
                $.post(url,data,function (res){
                    if(res.total>0){
                        let data = res.list[0]
                        let form = that.form||{}
                        for(let key in data){
                            if(form[key]!==undefined){
                                form[key] = data[key]
                            }
                        }
                        that.form = form
                    }
                    if(callback){
                        callback()
                    }
                })
            }
        },
        getQueryParameterAsJson() {
            let query = window.location.search.substring(1);
            if(!query){
                query = {}
            }else{
                query = query.split('&');
                query = query.map(function(item) {
                    return item.split('=');
                });
                let obj = {};
                query.forEach(function(item) {
                    obj[item[0]] = item[1];
                });
                query = obj;
            }
            return query;
        },
        /**
         * 获取表单信息
         */
        getFormInfo(){
            let form = this.form;
            if(form&&form!==null&&form!==undefined&&form!==''&&form!=={}){
                if(row!=null){
                    for(let key in form){
                        form[key] = row[key]
                    }
                    this.form = form
                }
            }else{
                if(row!=null){
                    this.form = row
                }
            }
        },
        /**
         * 获取时间
         * @param str
         * @param dayJoin
         * @param hJoin
         * @returns {string}
         */
        getDate(str,dayJoin='-',hJoin=':'){
            str = str+``
            var num = parseFloat(str);
            if(!isNaN(num) && isFinite(num) && num.toString() === str){
                let date = new Date(num * 1000);
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                let hour = date.getHours();
                let minute = date.getMinutes();
                let second = date.getSeconds();
                return year + dayJoin + month + dayJoin + day + ' ' + hour + hJoin + minute + hJoin + second
            }else{
                return str
            }
        },
        /**
         * 获取数据
         * @param url
         * @param data
         * @param callback
         */
        get(url,data={},callback=null,loading=true){
            if(!callback){
                if((typeof data)==='function'){
                    callback = data
                    data = null
                }
            }
           let loadObj = null
            if(loading){
                loadObj = this.$loading()
            }
            if(url.includes('?')===false){
                if(data!=={}&&data!==null&&data!==undefined&&data!==''){
                    url = url+'?'+$.param(data)
                }
            }else{
                if(data!=={}&&data!==null&&data!==undefined&&data!==''){
                    url = url+'&'+$.param(data)
                }
            }
            let that = this;
            $.post(url,function (res){
                if(loadObj){
                    loadObj.close()
                }
                if(res.code==1){
                    if(callback){
                        callback(res.data)
                    }

                }else{
                    that.$message({
                        message: res.msg?res.msg:"操作失败",
                        type: 'error'
                    })
                }
            })
        },
        /**
         * 打开页面
         * @param url
         * @param option
         */
        open2(url,option={}){
            if(option.callback){
                window.callback = option.callback
            }
            if(option.success){
                window.success = option.success
            }
            if(option.cancel){
                window.cancel = option.cancel
            }
            if(option.end){
                window.end = option.end
            }
            if(option.close){
                window.close = option.close
            }
            if(url.indexOf('http')==-1){
                url = Config.moduleurl+'/'+url;
            }
            option.title = option.title||'页面'
            option.shadeClose = option.shadeClose||true
            option.shade = option.shade||0.8
            option.area = option.area||['50%','95%']
            option.success = option.success||null
            option.cancel = option.cancel||null
            option.end = option.end||null
            option.close = option.close||null
            option.content = url
            option.type = option.type||2
            layer.open(option)

        },
        //上传图片成功
        handleFileSuccess(response,uploadFile,field){
            console.log('response',response,'uploadFile',uploadFile,'field',field)
            if(response.code==1){
                let url = response.data.url
                if(field){
                    this.form[field] = url
                }else{
                    this.form.img = url
                }
                console.log(this.form,'fffffffffffffff')
            }
        },
        //移除图片
        handleRemove(uploadFile, uploadFiles,field){
            console.log(uploadFile,uploadFiles,field)
            let url = uploadFile.response.data.url;
            let files = this.form[field]
            if(files.indexOf(url)!=-1){
                files.splice(files.indexOf(url),1)
            }
        },
        //多文件上传
        handleFileSuccessMultiple(response,uploadFile,field){
            console.log(response)
            if(response.code==1){
                let url = response.data.url
                if(field){
                    this.form[field].push(url)
                }else{
                    this.form.imgs.push(url)
                }
            }
        },
        // 获取图片
        getImg(url=''){
            if(!url){
                return ''
            }
            if(url.indexOf('http') === -1){
                url = Config.upload.cdnurl+url
            }
            return url
        },
        // 获取多张图片
        getImgs(urls=''){
            if(!urls){
                return ''
            }
            if((typeof urls)==='string'){
                urls = urls.split(',')
            }
            if(urls.length>0){
                urls = urls.map(function (item){
                    if(item){
                        if(item.indexOf('http') === -1){
                            item = Config.upload.cdnurl+item
                        }
                    }
                    return item
                })
            }
            return urls
        },
        delay(callback=null,time=500){
            if(callback){
                setTimeout(function () {
                    callback()
                },time)
            }
        },
        /**
         * 获取字典
         * @param key
         * @returns {Promise<*>}
         */
        getDictList(key='',field=null){
            let url = Config.domain+Config.dict_url+'/get_option?key='+key
            let that = this;
            $.get(url,function (res){
                that.changeForm[field] = res
                // console.log(that.changeForm)
            })
        },
         getFielsOption(){
            // console.log('getFielsOption')
            let getOptionsFielsd = this.getOptionsFielsd;
            for(let i in getOptionsFielsd){
                this.getFielsOptionOne(i,getOptionsFielsd[i])
            }
        },
        getFielsOptionOne(field,value){
            let that = this;
            let url = Config.domain+Config.base_url+`/get_option?field=${field}&is_switch=${value.is_switch}`;
            $.get(url,function (res){
                // console.log(res)
                that.getOptionsFielsd[field].options = res
            })
        },
        /**
         * 获取关联数据
         * @param e
         * @param field
         */
        remoteMethod(e,field,ids=''){
            console.log(e,field,'eeeeeeeeeeeee')
            let that = this
            let url = Config.domain+Config.base_url+`/get_with_datas?field=${field}&keyword=${e}&ids=${ids}`;
            $.get(url,function (res){
                that.getWithFields[field].options = res;
            })
        },
        /**
         * 获取关联数据
         */
        getWithDatas(){
            let getWithFields = JSON.parse(JSON.stringify(this.getWithFields))
            for(let i in getWithFields){
                this.remoteMethod('',i,this.form[i])
            }
        }
    }
    return common
})